package com.pybox.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.pybox.common.utils.JdbcTemplateUtils;
import com.pybox.common.utils.ParamUtils;
import com.pybox.dto.ExportClientLogsDto;
import com.pybox.dto.Result;
import com.pybox.dto.TCanbinetEventLogsDto;
import com.pybox.entity.TCanbinetEventLogs;
import com.pybox.entity.TEventCategroy;
import com.pybox.repository.*;
import com.pybox.util.FileUtils;
import com.pybox.util.HttpSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：TCanbinetEventLogs Service
 *
 * @author wuyingkai
 * @date 2018-09-15
 */

@Service
@Transactional
@Slf4j
public class TCanbinetEventLogsService {

    @Autowired
    private TCanbinetEventLogsRepository repository;

    @Autowired
    private TEventCategroyRepository eventCategroyRepository;
    @Autowired
    private JdbcTemplateUtils jdbcTemplateUtils;

    /**
     * 创建TCanbinetEventLogs
     *
     * @param source
     * @return
     */
    public boolean create(TCanbinetEventLogsDto source) {

        TCanbinetEventLogs target = new TCanbinetEventLogs();
        BeanUtils.copyProperties(source, target);
        repository.save(target);

        return true;

    }

    /**
     * 根据ID删除TCanbinetEventLogs
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id) {

        repository.delete(id);

        return true;

    }

    /**
     * 更新TCanbinetEventLogs
     *
     * @param id
     * @param source
     * @return
     */
    public boolean update(Integer id, TCanbinetEventLogsDto source) {

        TCanbinetEventLogs exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        BeanUtils.copyProperties(source, exist, new String[]{"id"});
        repository.save(exist);

        return true;

    }

    /**
     * 根据ID查询TCanbinetEventLogs
     *
     * @param id
     * @return
     */
    public TCanbinetEventLogsDto detail(Integer id) {

        TCanbinetEventLogs exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        TCanbinetEventLogsDto target = new TCanbinetEventLogsDto();
        BeanUtils.copyProperties(exist, target);

        return target;

    }

    /**
     * 分页查询查询TCanbinetEventLogs
     *
     * @param pageNo
     * @param pageSize
     * @param paramMap
     * @return
     */
    public Page<TCanbinetEventLogsDto> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap) {

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);

        List<Object> object = new ArrayList<>();
        StringBuffer sql = new StringBuffer(" SELECT\n" +
                "\tl.id,\n" +
                "\tl.ctime,\n" +
                "\tu.realname AS userName,\n" +
                "\tu2.realname AS operateName,\n" +
                "\tl.obj_name,\n" +
                "\tc.NAME AS cabinetName,\n" +
                "\tl.ROW,\n" +
                "\tl.col,\n" +
                "\tl.pos,\n" +
                "\te.`name` AS eventName \n" +
                "FROM\n" +
                "\tt_canbinet_event_logs l\n" +
                "\tLEFT JOIN t_users u ON ( l.user_id = u.id )\n" +
                "\tLEFT JOIN t_users u2 ON ( l.user2_id = u2.id )\n" +
                "\tLEFT JOIN t_cabinets c ON ( c.id = l.cabinet_id )\n" +
                "\tLEFT JOIN t_event_categroy e ON ( e.id = l.`event` ) WHERE 1 = 1");
        String where = new ParamUtils().getParams(sql, paramMap);

        Page<TCanbinetEventLogsDto> data = jdbcTemplateUtils.page(where, object, TCanbinetEventLogsDto.class, pageNo, pageSize);

        Page<TCanbinetEventLogsDto> page = new PageImpl<>(data.getContent(), pageable, data.getTotalElements());


        return page;

    }

    /**
     * 确认告警
     *
     * @param id
     * @return
     */
    public Result<Boolean> updateStateById(Integer id) {
        repository.updateStateById(id);
        return Result.ok(true);
    }

    /**
     * 确认全部告警
     *
     * @return
     */
    public Result<Boolean> updateAllState() {
        repository.updateAllState();
        return Result.ok(true);
    }

    /**
     * 导出日志
     *
     * @param response
     */
    public void downExcel(HttpServletResponse response,Map<String, String> paramsMap) throws IOException {
        List<Object> object = new ArrayList<>();
        StringBuffer sql = new StringBuffer(" SELECT\n" +
                "\tl.ctime,\n" +
                "\tu.realname AS userName,\n" +
                "\tu2.realname AS operateName,\n" +
                "\tl.obj_name,\n" +
                "\tc.NAME AS cabinetName,\n" +
                "\tl.ROW,\n" +
                "\tl.col,\n" +
                "\tl.pos,\n" +
                "\te.`name` AS eventName \n" +
                "FROM\n" +
                "\tt_canbinet_event_logs l\n" +
                "\tLEFT JOIN t_users u ON ( l.user_id = u.id )\n" +
                "\tLEFT JOIN t_users u2 ON ( l.user2_id = u2.id )\n" +
                "\tLEFT JOIN t_cabinets c ON ( c.id = l.cabinet_id )\n" +
                "\tLEFT JOIN t_event_categroy e ON ( e.id = l.`event` ) WHERE 1 = 1");

        String where = new ParamUtils().getParams(sql, paramsMap);

        List<ExportClientLogsDto> list = jdbcTemplateUtils.list(where, object, ExportClientLogsDto.class);

        //指定列表标题和工作表名称
        ExportParams params = new ExportParams("客户端日志表", "客户端日志表");
        Workbook workbook = ExcelExportUtil.exportExcel(params, ExportClientLogsDto.class, list);

        //下载导出 设置头信息
        String filename = "客户端日志表.xls";
        String agent = HttpSessionUtil.getRequest().getHeader("user-agent");
        filename = FileUtils.encodeDownloadFilename(filename, agent);
        response.setHeader("content-Disposition", "attachment;filename=" + filename);

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    public Result<Integer> getUnCheckCount(Integer customerId) {
        Integer count = repository.getUnCheckCount(customerId);
        return Result.ok(count);
    }

    public Result<Integer> getUnCheckCount() {
        Integer count = repository.getUnCheckCount();
        return Result.ok(count);
    }

    public String getEventName(String eventId) {
        String language = HttpSessionUtil.getRequest().getHeader("Accept-Language");
        TEventCategroy tEventCategroy = eventCategroyRepository.findOne(Integer.parseInt(eventId));
        String eventName = "";
        if (null != tEventCategroy) {
            JSONObject jsonObj = JSONObject.parseObject(tEventCategroy.getI18n());
            //获取i18n国际化，根据header请求拿到语言返回对应的name
            if (jsonObj != null && (language.contains("zh") || language.contains("zh-cn"))) {
                log.info("使用的是中文");
                eventName = jsonObj.getString("zh-cn");
            } else if (jsonObj != null && (language.contains("en") || language.contains("en-us"))) {
                log.info("使用的是英文");
                eventName = jsonObj.getString("en-us");
            } else {
                log.info("header没取到语言，默认使用的是中文");
                eventName = tEventCategroy.getName();
            }
        }
        return eventName;
    }

}